<template>
	<view class="u-p-x-15 u-p-y-32 page">
		<image v-if="info.nft_image" :src="info.nft_image" style="width:100%;height:720rpx"></image>
		<image v-else src="../static/images/zs.jpg" style="width:100%;height:720rpx"></image>
		<view class=" u-m-t-40">
			<!-- <button class="detail-btn" @click="casting = true">铸造</button> -->
			<button class="detail-btn" @click="handleMint" v-if="info.mint_status==0 && !_id">铸造</button>
			<button class="detail-btn" @click="handleZs" v-if="info.mint_status==1 && !_id">赠送</button>
			<button class="detail-btn" @click="handleReceive" v-if="_id">领取</button>
			<view class="detail-info gray-bg">
				<view class="flex align-center justify-between item">
					<text>剩余贡献值</text>
					<text>{{info.contribution_total || 0}}贡献值</text>
				</view>
				<view class="flex align-center justify-between item" v-if="info.mint_status==1">
					<text>累计获得</text>
					<text>{{info.mining_income_total || 0}} 消费积分</text>
				</view>
			</view>
			<view class="detail-info gray-bg" v-if="info.mint_status==1">
				<view class="flex align-center justify-between item" v-if="contractAddress">
					<text>合约地址</text>
					<text>{{shortAddress(contractAddress)}}</text>
				</view>
				<view class="flex align-center justify-between item">
					<text>NFT ID</text>
					<text>{{info.nft_code || '-'}}</text>
				</view>
				<view class="flex align-center justify-between item">
					<text>区块链</text>
					<text>BNB链</text>
				</view>
				<view class="flex align-center justify-between item">
					<text>铸造时间</text>
					<text>{{info.minttime || '-'}}</text>
				</view>
			</view>
		</view>
		<view class="u-m-y-50 divider"></view>
		<view class="u-p-x-15 u-m-t-40" v-if="type=='order'">
			<view class="">
				<view v-for="(item,index) in details.store_info" :key="index">
					<block v-for="(v, indey) in item" :key="indey">
						<text class="flex font" v-if="indey == 0 && v.merch_name">{{v.merch_name}}</text>
						<order-item-list-good :item="v"></order-item-list-good>
						<view class="flex align-center justify-end text-center ">
							<text
								class="text-danger u-p-b-20">{{v.is_weiquan == 2?'维权成功': v.is_weiquan == 1?'维权中': ''}}</text>
						</view>
					</block>
				</view>
			</view>
			<view class="">
				<dy-cell-item fontSize="26rpx" leftTitle="商品总价" :rightTitle="`¥${details.total_price}`"
					:rightIcon="false"></dy-cell-item>
				<dy-cell-item class="address" fontSize="26rpx" leftTitle="收货信息" :rightTitle="`${address}`"
					:rightIcon="false"></dy-cell-item>
				<dy-cell-item fontSize="26rpx" leftTitle="运费" :rightTitle="`${expressPrice}`"
					:rightIcon="false"></dy-cell-item>
				<dy-cell-item fontSize="26rpx" leftTitle="店铺优惠" :rightTitle="`-¥${details.coupon_price}`"
					:rightIcon="false"></dy-cell-item>
				<dy-cell-item leftColor="#333" fontSize="26rpx" leftTitle="实付金额" :rightTitle="`¥${details.pay_price}`"
					rightColor="#FF6600" :rightIcon="false"></dy-cell-item>
			</view>
			<view class="u-border-top u-p-t-20" v-if="details.text != '已完成'">
				<text class="flex font-weight-bold u-p-y-8">订单信息</text>
				<!-- <dy-cell-item leftTitle="订单备注" :rightTitle="details.note" :rightIcon="false"></dy-cell-item> -->
				<view class="flex align-center justify-between">
					<text class="text-greey u-m-t-15">订单备注</text>
					<view class="flex justify-end" style="width: 500rpx;">
						<text style="word-break: break-all;">{{details.note}}</text>
					</view>
				</view>
				<view class="flex align-center justify-between">
					<view class="flex-1">
						<dy-cell-item leftTitle="订单编号" :rightTitle="details.order_no" :rightIcon="false"></dy-cell-item>
					</view>
					<u-tag class="u-m-l-30" text="复制" size="mini" @click="$copy(details.order_no)"></u-tag>
				</view>
				<dy-cell-item leftTitle="创建时间" :rightTitle="details.creattime_text" :rightIcon="false"></dy-cell-item>
				<template v-if="details.receipt_time_text">
					<dy-cell-item leftTitle="成交时间" :rightTitle="details.receipt_time_text"
						:rightIcon="false"></dy-cell-item>
				</template>
				<template v-if="details.pay_img">
					<image src="" mode=""></image>
				</template>
			</view>
		</view>
		<view v-if="type=='goods'">
      <view class="flex u-p-20 u-m-b-20 bg-white rounded-10">
        <image v-if="info.goods_spec.image" :src="info.goods_spec.image" class="u-image border" style="width: 90px; height: 90px; border-radius: 2px; overflow: hidden; opacity: 1; transition: opacity 0.5s ease-in-out; background-color: transparent;"/>
        <view class="flex-1 flex flex-column justify-between u-p-x-20">
          <text class="u-font-28 text-ellipsis-2" style="height: 40px; width: 225px;">{{ info.goods_spec.goods_name }}</text>
          <text class="u-p-y-10 u-font-26 text-danger font-weight-bold">{{ info.goods_spec.goods_price }}</text>
        </view>
      </view>
		</view>
		<u-popup v-model="giftshow" mode="center" border-radius="14" width="720rpx" @close="handleCloseGift">
			<view class="u-p-20 popup-box">
				<view>
					<view class="detail-info gray-bg">
						<view class="item flex flex-column">
							<text>赠送给</text>
							<input v-model="giftInput" placeholder="请输入钱包地址或手机号" style="border-radius: 16rpx;"
								class="border u-p-16 u-m-t-20 font-26" />
						</view>
						<view class="flex align-center justify-between item">
							<text>NFT数量</text>
							<text>1</text>
						</view>
						<view class="flex align-center justify-between item">
							<text>剩余贡献值</text>
							<text>{{info.contribution_total || 0}}</text>
						</view>
						<view class="flex align-center justify-between item">
							<text>Gas费</text>
							<text>{{estimatedGas || 0}} 积分</text>
						</view>
					</view>
					<button class="btn-primary" @click="handleInputPwd">赠送</button>
				</view>
				<view class="popup-header">
					<text>赠送</text>
					<view class="popup-close" @click="giftshow=false">
						<uni-icons type="closeempty" size="20"></uni-icons>
					</view>
				</view>
			</view>
		</u-popup>
		<u-popup v-model="casting" mode="center" border-radius="14" width="720rpx" @close="casting=false">
			<view class="u-p-20 popup-box">
				<view>
					<view class="detail-info gray-bg">
						<view class="flex align-center justify-between item">
							<text>NFT数量</text>
							<text>1</text>
						</view>
						<view class="flex align-center justify-between item">
							<text>剩余贡献值</text>
							<text>{{info.contribution_total || 0}}</text>
						</view>
						<!-- <view class="flex align-center justify-between item">
							<text>Gas费</text>
							<text>{{estimatedGas || 0}} 积分</text>
						</view> -->
					</view>
					<button class="btn-primary" @click="handleSubmitMint">铸造</button>
				</view>
				<view class="popup-header">
					<text>铸造</text>
					<view class="popup-close" @click="casting=false">
						<uni-icons type="closeempty" size="20"></uni-icons>
					</view>
				</view>
			</view>
		</u-popup>
		<u-popup v-model="walletshow" mode="center" border-radius="14" width="720rpx" @close="handleCloseWallet">
			<view class="u-p-20 popup-box">
				<view>
					<view class="detail-info">
						<input type="password" v-model="passwordInput" placeholder="请输入钱包密码"
							style="border-radius: 16rpx;" class="border u-p-16 u-m-t-20 font-26" />
					</view>
					<button class="btn-primary" @click="handlegift">确定</button>
				</view>
				<view class="popup-header">
					<text>钱包密码</text>
					<view class="popup-close" @click="walletshow=false">
						<uni-icons type="closeempty" size="20"></uni-icons>
					</view>
				</view>
			</view>
		</u-popup>
		<u-popup v-model="scanshow" mode="center" border-radius="14" width="720rpx" @close="handleBack">
			<view class="u-p-20 popup-box">
				<view>
					<view class="detail-info">
						<view class="flex flex-column align-center">
							<image src="../static/images/zs.jpg" style="width: 180rpx;height:180rpx"></image>
							<view class="u-m-y-20">恭喜您获得NFT</view>
						</view>
					</view>
					<button class="btn-primary" @click="handleBack">确定</button>
				</view>
				<view class="popup-header">
					<text>获得NFT</text>
					<view class="popup-close" @click="handleBack">
						<uni-icons type="closeempty" size="20"></uni-icons>
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		mapGetters,
	} from 'vuex'
	import {
		NftWalletApi
	} from "@/api/modules/NftWallet.js"
	import {
		validateWalletPassword,
		shortAddress,
		copyDownloadUrl,
    decryptAES
	} from "@/common/utils/utils.js"
	import BLOCK_CONFIG from "@/config/block.js";
	import {
		ethers
	} from "ethers";
	import {
		ServerWalletApi
	} from "@/api/modules/ServerWallet.js"
	import orderItemListGood from "./components/order-item-list-good.vue"
import { count } from 'console';
	export default {
		components:{
			'order-item-list-good':orderItemListGood
		},
		data() {
			return {
				copyDownloadUrl,
				shortAddress,
				giftInput: "",
				scanshow: false,
				walletshow: false,
				casting: false,
				giftshow: false,
				order_no: '',
				details: {
					address: {}
				},
				info: {
					contribution_total: 0
				},
				uid: null,
				id: null,
				type: null,
				_id: null,
				giftParams: {
					nft_id: "",
					to_user_mobile: "",
					to_user_addr: "",
					type:""
				},
				passwordInput: "",
				estimatedGas: "",
				params:{}, // 二维码参数
			}
		},
		onLoad(options) {
			const {
				id,
				type,
				_id,
				tjname
			} = options
			if (id) {
				this._id = _id || null
				this.id = id || null
				this.giftParams.nft_id = id || null
				this.type = type || null
				this.giftParams.type = this.type
				this.handleFetchDetail()
				this.handleFetchGasPrice()
			} else if(options.scene){
				let url = decodeURIComponent(decodeURIComponent(options.scene))
				let scene = url.split('&')
				scene.forEach(item=>{
					let o = item.split('=')
					this.params[o[0]] = o[1]
				})
				console.log('scene', this.params);
				if (this.params.t && this.params.d && this.params.i) {
					this.uid = this.params.t	//推广用户id
					this._id = this.params.i	//nft _id,只有后8位
					this.id = this.params.d	//nft goods_nft_id
					this.type = 'goods_nft'
					this.giftParams.nft_id = this.id || null
					this.giftParams.type = this.type
				}
				let b = uni.getStorageSync('token')
				if(!b){
					this.$Toast('请先登录')
					setTimeout(()=>{
						uni.navigateTo({
							url:'/pages/login/login/loginWeixin?isPay=1&tjuid='+this.params.t+'&type=goods_nft'
						})
					},500)
				}
			}
		},
		computed: {
			...mapGetters({
				walletAddress: "user/getWalletAddress",
				nftConfig: "user/getNftConfig"
			}),
			contractAddress() {
        if(this.nftConfig.nft){
          const toIndex = this.nftConfig.nft.findIndex(item => item.name == "LK")
				  return this.nftConfig.nft[toIndex].contract || '-'
        }else{
          return null
        }
			},
			expressPrice() {
				if(this.details){
          if (this.details.express_price <= 0) return '包邮'
				  return "¥" + this.details.express_price
        }else{
          return null
        }
			},
			address() {
				if(this.details){
          return this.details.address.name + ',' + this.details.address.phone + ',' + this.details.address.province +
					' ' + this.details.address.city + ' ' + this.details.address.area + ' ' + this.details.address.detail
        }else{
          return null
        }
			}
		},
		methods: {
			
			handleMint() {
				// #ifdef MP-WEIXIN
				uni.showModal({
					title: "操作需要钱包功能",
					content: "小程序版本不支持钱包，仅供查看,您可在APP中进行操作",
					cancelText: "下载APP",
					success: (res) => {
						if (res.cancel) {
							this.copyDownloadUrl()
						}
					}
				})
				// #endif
				// #ifndef MP-WEIXIN
				this.casting = true
				// #endif
			},
			handleZs() {
				// #ifdef MP-WEIXIN
				uni.showModal({
					title: "操作需要钱包功能",
					content: "小程序版本不支持钱包，仅供查看,您可在APP中进行操作",
					cancelText: "下载APP",
					success: (res) => {
						if (res.cancel) {
							this.copyDownloadUrl()
						}
					}
				})
				// #endif
				// #ifndef MP-WEIXIN
				this.giftshow = true
				// #endif
			},
			async handleReceive() {
				if (!this._id) return this.$Toast("商品NFT的id不存在")
				const params = {
					goods_nft_id: this.id,
					_id: this._id
				}
				const res = await NftWalletApi.receiveNft(params)
				if (res.code == 1) {
					this.scanshow = true
				} else {
					this.$Toast(res.msg)
				}
			},
			handleBack() {
				//uni.navigateBack()
				uni.navigateTo({
					url:'/pages/mine/mineBalance/nft/nft'
				})
				// uni.switchTab({
				//   url: '/pages/tabbar/mine/mine'
				// });
			},
			async handleFetchGasPrice() {
				const res = await NftWalletApi.getGasPrice()
				if (res.code == 1) {
					this.estimatedGas = res.data.cost
				} else {
					this.$Toast(res.msg)
				}
			},
			handleSubmitMint() {
				this.walletshow = true
				this.casting = false
			},
			handleCloseGift() {
				this.giftshow = false
				this.giftInput = ""
			},
			handleCloseWallet() {
				this.walletshow = false
				this.passwordInput = ""
			},
			validateAddress(input) {
				const isWalletAddress = /^0x[a-fA-F0-9]{40}$/.test(input);
				const isPhoneNumber = /^[0-9]{11}$/.test(input);
				if (isWalletAddress) {
					return "wallet";
				} else if (isPhoneNumber) {
					return "phone";
				} else {
					return "invalid";
				}
			},
			async handleFetchDetail() {
				this.$ShowLoading()
				const res = await NftWalletApi.getNftDetail(this.id, this.type)
				this.$HideLoading()
				if (res.code == 1) {
					this.details = res.data.order
					this.info = res.data
				} else {
					this.$Toast(res.msg)
				}
			},
			resetGiftForm() {
				this.giftInput = "";
				this.passwordInput = "";
				this.giftshow = false;
				this.walletshow = false;
				this.casting = false;
			},
			async mintTokens() {
				console.log('测试1111111');
				this.$ShowLoading()
				try {
					const {
						name
					} = BLOCK_CONFIG.rpcInfo;
					const res = await NftWalletApi.getUserWallet();
					if (res.code !== 1) {
						this.$Toast(res.msg);
						return;
					}
					console.log('55555555', res);
					const {
						sk_key,
						password
					} = res.data;
					const result = await NftWalletApi.decrypt({
						data: password
					});
					if (result.code !== 1) {
						this.$Toast(result.msg);
						return;
					}
					const privateKey=  await decryptAES(sk_key,result.data)
					try {
						let signer = new ethers.Wallet(privateKey);
						const toIndex = this.nftConfig.nft.findIndex(item => item.name == "LK")
						const ABI = this.nftConfig.nft[toIndex].abi
						const contractInterface = new ethers.Interface(ABI)
						const resd = await NftWalletApi.nftMint(this.info.nft_code,this.type)
						console.log('33333333', resd);
						if (resd.code == 1) {
							const {
								data
							} = resd
							if (typeof data === 'string') return this.$Toast(resd.msg)
							const {
								nft_id,
								nonce,
								signature
							} = data
							
							const txData = contractInterface.encodeFunctionData('mintNFT', [nft_id,
								nonce, signature
							])
							const result = await uni.request({
								url: this.nftConfig.rpcurl,
								method: 'POST',
								header: {
									'Content-Type': 'application/json' // 必须设置这个请求头
								},
								data: JSON.stringify({
									jsonrpc: "2.0",
									method: "eth_getTransactionCount",
									params: [signer.address, "latest"],
									id: 1
								}),
							})
							console.log('22222222', Number(result[1].data.result));
							const nonces = Number(result[1].data.result)
							const gasPriceRes = await ServerWalletApi.getWalletGasPrice()
							const chainId = this.nftConfig.chain_id
							console.log('333333', gasPriceRes.data.gas_price_gwei);
							const tx = {
								nonce: nonces,
								gasPrice: ethers.parseUnits(gasPriceRes.data.gas_price_gwei,
									"gwei"),
								gasLimit: 1000000,
								to: this.nftConfig.nft[toIndex].contract,
								value: ethers.parseEther("0"),
								data: txData,
								chainId: chainId
							}
							
							try {
								const signedTx = await signer.signTransaction(tx)
								const resu = await uni.request({
									url: this.nftConfig.rpcurl,
									method: 'POST',
									header: {
										'Content-Type': 'application/json' // 必须设置这个请求头
									},
									data: JSON.stringify({
										jsonrpc: "2.0",
										method: "eth_sendRawTransaction",
										params: [signedTx],
										id: 2
									}),
								})
								console.log('111111111', resu[1].data);
								if (resu[1].data.error) {
									this.$Toast("交易失败2")
								} else if (resu[1].data.result) {
									const hash = resu[1].data.result
									await this.updateBackendStatus(hash);
								}
							} catch (error){
								console.log(error)
								this.$Toast("交易失败1")
							} finally {
								this.$HideLoading()
							}
						} else {
							this.$Toast(resd.msg)
						}
					} catch (error) {
						console.log(error)
						this.$Toast("铸造失败")
					}
				} catch (error) {
					this.$Toast("发生错误，请稍后再试");
				}
			},
			async updateBackendStatus(hashs) {
				this.$ShowLoading()
				const res = await NftWalletApi.updateMintStatus(this.id, hashs,this.type)
				this.$HideLoading()
				if (res.code == 1) {
					this.passwordInput = ""
					this.walletshow = false
					this.casting = false
					uni.showModal({
						title: "NFT铸造成功",
						showCancel: false,
						success: (res) => {
							if (res.confirm) {
								this.handleFetchDetail()
							}
						},
					})
				} else {
					this.$Toast(res.msg)
				}
			},
			async handlegift() {
				try {
					this.$ShowLoading();
					if (!this.passwordInput.trim()) return this.$HideLoading()
					const res = await validateWalletPassword(this.passwordInput);
					if (!res || res.code !== 1) {
						this.$Toast(res?.msg || "验证失败");
						return;
					}
					this.$HideLoading()
					// 判断是铸造还是赠送
					if (this.info.mint_status === '1') {
						const result = await NftWalletApi.donation(this.giftParams);
						if (result.code !== 1) {
							this.$Toast(result.msg);
							return;
						}
						this.resetGiftForm();
						uni.showModal({
							title: "NFT赠送成功",
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									uni.navigateBack()
								}
							},
						});
					} else if (this.info.mint_status === '0') {
						await this.mintTokens()
					}
				} catch (error) {
					console.log(error)
					this.$Toast("发生错误，请稍后再试");
					this.$HideLoading();
				} finally {
					this.$HideLoading();
				}
			},
			handleInputPwd() {
				const status = this.validateAddress(this.giftInput)
				if (status == 'wallet') {
					this.giftParams.to_user_addr = this.giftInput
				} else if (status == 'phone') {
					this.giftParams.to_user_mobile = this.giftInput
				} else if (status == 'invalid') {
					return this.$Toast("请输入正确的赠送地址或手机号")
				}
				this.walletshow = true
				this.giftshow = false
				this.casting = false
			}
		}
	}
</script>

<style scoped lang="scss">
	.page {
		background-color: #fff;
		min-height: 100vh;
	}

	.detail-btn {
		background-color: var(--mainColor);
		font-size: 28rpx;
		display: block;
		color: #fff;
	}

	.item {
		margin-bottom: 40rpx;

		text {
			color: #333;
			font-size: 32rpx;
		}

		text:first-child {
			color: #999;
			font-size: 28rpx;
		}

		&:last-child {
			margin-bottom: 0;
		}
	}

	.detail-info {
		margin-top: 40rpx;
		border-radius: 16rpx;
		padding: 40rpx;
	}

	.gray-bg {
		background: rgba(0, 0, 0, 0.02);
	}

	.popup-box {
		position: relative;
	}

	.popup-header {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		padding: 20rpx;
		background-color: #fff;
		display: flex;
		align-items: center;
		justify-content: center;

		text {
			font-size: 28rpx;
		}

		.popup-close {
			position: absolute;
			top: 50%;
			right: 20rpx;
			transform: translateY(-50%);
		}
	}

	.btn-primary {
		font-size: 28rpx;
		color: #fff;
		background-color: var(--mainColor);
		margin-top: 80rpx;
	}

	.divider {
		height: 2rpx;
		background-color: #eee;
	}
</style>